package org.je.dev.image;

import java.awt.image.BufferedImage;
import org.je.util.NumberUtil;

/**
 * @author fanyifeng
 */
public class FastImageUtil
{
	/**
	 * @param data
	 * @return fimg
	 */
	public static FastImage toFastImage(byte[] data) {
		return toFastImage(data ,0);
	}

	/**
	 * @param data
	 * @return fastImage
	 */
	public static FastImage toFastImage(byte[] data, int off) {
		int w = NumberUtil.bytes2int(data ,off);
		int h = NumberUtil.bytes2int(data ,off + 4);
		
		FastImage img = new FastImage(w,h);
		byte[] rgbs = img.rgbs();
		byte[] alphas = img.alphas();

		int i = 8 + off, rgbOff = 0, count = 0;

		for (; count < alphas.length; ++count, rgbOff += 3) {
			alphas[count] = data[i];
			if (data[i] == zero[0]) {
				System.arraycopy(zero ,0 ,rgbs ,rgbOff ,3);
				++i;
			} else {
				rgbs[rgbOff] = data[i + 1];
				rgbs[rgbOff + 1] = data[i + 2];
				rgbs[rgbOff + 2] = data[i + 3];
				i += 4;
			}
		}
		return img;
	}

	/**
	 * @param img
	 * @return fastImage
	 */
	public static FastImage toFastImage(BufferedImage img) {
		return toFastImage(img ,img.getWidth() ,img.getHeight());
	}

	/**
	 * @param img
	 * @param w
	 * @param h
	 * @return fastImg
	 */
	public static FastImage toFastImage(BufferedImage img, int w, int h) {
		FastImage rst = new FastImage(w,h);
		int eY = NumberUtil.min(h ,img.getHeight());
		int eX = NumberUtil.min(w ,img.getWidth());
		for (int y = 0; y < eY; ++y) {
			for (int x = 0; x < eX; ++x) {
				rst.setARGB(x ,y ,img.getRGB(x ,y));
			}
		}
		return rst;
	}

	public static final int		TEMP_BUFFERED_IMAGE_TYPE	= BufferedImage.TYPE_INT_ARGB;

	private static final byte[]	zero						= new byte[] { 0, 0, 0 };
}
